<template>
	<el-card shadow="never">
		<el-form
            :inline="true"
            :model="state.queryForm"
            @keyup.enter="onSearch()">
			<el-form-item>
				<el-input
                    v-model="state.queryForm.dictType"
                    placeholder="字典类型"
                    clearable>
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-input
                    v-model="state.queryForm.dictName"
                    placeholder="字典名称"
                    clearable>
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="onSearch()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onHandle()">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="deleteBatch()">删除</el-button>
			</el-form-item>
		</el-form>
		<el-table
			v-loading="state.loading"
			:data="state.dataList"
			border
			style="width: 100%"
			@selection-change="selectionIds"
			@sort-change="onSortChange"
		>
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="dictType" label="字典类型" header-align="center" align="center"> </el-table-column>
			<el-table-column prop="dictName" label="字典名称" header-align="center" align="center"></el-table-column>
			<el-table-column prop="remark" label="备注" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="dictSource" label="数据来源" header-align="center" align="center">
				<template #default="scope">
					<span v-if="scope.row.dictSource === 0">字典数据</span>
					<span v-else>动态SQL</span>
				</template>
			</el-table-column>
			<el-table-column prop="sort" label="排序" sortable="custom" header-align="center" align="center"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center" width="180">
                <template #default="scope">
                    {{ scope.row.createTime.replace('T', ' ').split('+')[0] }}
                </template>
            </el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
				<template #default="scope">
					<el-button v-if="scope.row.dictSource === 0" type="primary" link @click="showDictData(scope.row)">字典配置</el-button>
					<el-button v-if="scope.row.dictSource === 1" type="primary" link @click="showDataSql(scope.row)">动态数据</el-button>
					<el-button type="primary" link @click="onHandle(scope.row.id)">修改</el-button>
					<el-button type="primary" link @click="deleteBatch(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
         <div style="margin-top: 20px;">
            <el-pagination
                layout="prev, pager, next"
                v-model:current-page="pagination.page"
                :page-size="pagination.limit"
                :total="pagination.total"
                @current-change="onPageChange"
                background
            >
            </el-pagination>
        </div>

		<!-- 新增 / 修改 -->
		<DictDlg ref="dictDlgRef" @refresh="getDataList" />

		<!-- 动态数据 -->
		<!-- <el-drawer v-if="dataSqlVisible" v-model="dataSqlVisible" :title="dataSqlTitle" :size="800" :close-on-press-escape="false">
			<data-sql :dict-type-id="dictTypeId"></data-sql>
		</el-drawer> -->

		<!-- 字典配置 -->
		<el-drawer
			v-if="dictDataVisible"
			v-model="dictDataVisible"
			:title="dictDataTitle"
			:size="800"
			:close-on-press-escape="false">
			<DictData :dict-type-id="dictTypeId" />
		</el-drawer>
	</el-card>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dictTypeStore } from '@/store/dict_type'
// import { dictDataStore } from '@/store/dict_data'
import DictDlg from './dict_dlg.vue'
import DictData from './dict_data.vue'

const useDictTypeStore = dictTypeStore() 

const state = reactive({ 
	loading: false, 
	queryForm: { // 查询表单
		dictType: '', // 字典类型
		dictName: '', // 字典名称
	},
    order: '',
    asc: false,		// 这两个用于排序
	dataList: [], // 数据列表
})
const pagination = reactive({ // 分页
	page: 1, 
	limit: 5, 
	total: 0, 
})

onMounted(() => {
	getDataList()
})

const getDataList = async () => { 
	state.loading = true; 
	try {
		// 如果要排序，还要加上 order 和 asc
		await useDictTypeStore.fetchDictTypePage({ 
            ...state.queryForm,
            order: state.order,
            asc: state.asc,
            page: pagination.page, 
            limit: pagination.limit, 
        })
		state.dataList = useDictTypeStore.dictTypeList
		pagination.total = useDictTypeStore.pagination.total
	} catch (error) { 
		console.error(error); 
	} finally { 
		state.loading = false; 
	}
}

const onSearch = () => {
	pagination.page = 1
	getDataList()
}

const keyIds = ref([])
const selectionIds = (selection) => {
	keyIds.value = selection.map((item) => item.id) 
    console.log(keyIds.value) 
}

const onPageChange = (val) => {
	pagination.page = val 
	getDataList() 
}

const onSortChange = (val) => {
    const { prop, order } = val
    state.order = prop && order ? prop : ''
    state.asc = order === 'ascending'
	// console.log(`排序：${state.order}， 升降序：${state.asc}`)
	getDataList()
}

const dictDlgRef = ref()
const onHandle = (id) => {
	if (id) { 
		dictDlgRef.value.init(id) // 修改模式
	} else { 
		dictDlgRef.value.init() // 新增模式
	}
}

const deleteBatch = async(key) => {
    const ids = key ? [key] : keyIds.value
    if (ids.length === 0) {
      ElMessage.warning('请选择删除记录')
      return
    }

	try {
		await ElMessageBox.confirm('确定进行删除操作?', '提示', {
			confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
		})

		await useDictTypeStore.deleteDictType(ids)
		ElMessage.success('删除成功')
	} catch(error) {
        if(error !== 'cancel') { 
            ElMessage.error(error.message || '删除失败')
        }
	}
}

const dictDataVisible = ref(false)
const dictDataTitle = ref()
const dictTypeId = ref()
const showDictData = (row) => {
	dictDataVisible.value = true
	dictTypeId.value = row.id
	dictDataTitle.value = '字典配置 - ' + row.dictType
}

const showDataSql = () => {}

</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
	height: 50px;
	margin-bottom: 0;
	padding: 0 15px;
    border-bottom: 1px solid var(--el-border-color);
}
</style>